/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-05-31 12:28:59
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-01 11:50:25
 * @FilePath: /hw/110/pipe/Shm_ipc/Fifo.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#ifndef _COMM_HPP_
#define _COMM_HPP_
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstring>
#include <errno.h>
#include<cassert>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

#define Mode 0666
#define Path "./fifo"

class Fifo
{
public:
    Fifo(const string &path = Path) : _path(path)
    {
        umask(0);
        // 创建管道
        int n = mkfifo(_path.c_str(), Mode);
        if (n == 0)
        {
            cout << "mkfifo success" << endl;
        }
        else
        {
            cerr << "mkfifo fail,errno:" << errno << ",errstring:" << strerror(errno) << endl;
        }
    }
    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if (n == 0)
        {
            cout << "removed success" << endl;
        }
        else
        {
            cerr << "remove fail,errno:" << errno << ",errstring:" << strerror(errno) << endl;
        }
    }

private:
    string _path;
};
class Sync
{
public:
    Sync()
        : _rfd(-1),
          _wfd(-1)
    {
    }
    void OpenReadOrDie()
    {
        _rfd = open(Path, O_RDONLY);
        if (_rfd < 0)
            exit(1);
    }
    void OpenWriteOrDie()
    {
        _wfd = open(Path, O_WRONLY);
        if (_wfd < 0)
            exit(1);
    }
    bool Wait()
    {
        bool ret=true;
        uint32_t c=0;
        ssize_t n=read(_rfd,&c,sizeof(uint32_t));
        if(n==sizeof(uint32_t))
        {
            cout<<"Server:: server wakeup, begin read shm..."<<endl;
        }
        else 
        {
            return false;
        }
        return true;
    }
    void WakeUp()
    {
        uint32_t c=0;
        ssize_t n=write(_wfd,&c,sizeof(c));
        assert(n==sizeof(uint32_t));

        cout<<"Client::  wakeup server......."<<endl;//唤醒服务端
    }
    ~Sync()
    {
    }

private:
    int _rfd;
    int _wfd;
};

#endif